package triannon.client.sprites;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import triannon.client.settings.LevelProperties;
import triannon.client.sprites.renderer.Renderers;
import triannon.client.util.DebugUtil;

public class Building extends LivingSprite {
	private int paintCycles = 0;

	public Building(String key, Fraction fraction) {
		this(key, fraction, 0, 0, 1d);
	}

	public Building(String key, Fraction fraction, int x, int y) {
		this(key, fraction, x, y, 1d);
	}

	public Building(String key, Fraction fraction, int x, int y, double health) {
		super(SpriteType.BUILDING, key, fraction, x, y, health);
	}

	@Override
	public void setAlreadyPainted(boolean alreadyPainted) {
		super.setAlreadyPainted(alreadyPainted);
		paintCycles = 0;
	}

	@Override
	public void paint(Graphics2D g) {
		// find out if this is the upper or lower part of this building
		boolean paintLowerPart = high && !alreadyPainted;
		boolean paintUpperPart = high && alreadyPainted;

		if (!alreadyPainted || (paintUpperPart && paintCycles < 2)) {
			alreadyPainted = true;
			paintCycles++;
			// render debug quad
			if (DebugUtil.getInstance().isRenderBuildingDebugQuads()) {
				g.setColor(Color.RED);
				g.drawRect(x, y, width, height);
			}

			// paint the selection only if this is not the upper part of an building
			if (!paintUpperPart) {
				// paint if the building is selected
				if (selected) {
					Renderers.getSelectionRenderer().paint(g, x, y, width, height);

					if (goToX >= 0 && goToY >= 0) {
						Renderers.getGoToRenderer().paint(g, getCenterX(), getCenterY(),
								goToX, goToY);
					}
					// paint if the building is going to be selected
				} else if (preSelected) {
					Renderers.getPreSelectionRenderer().paint(g, x, y, width, height);
				}
			}

			// save the old clip rectangle
			Rectangle oldClip = g.getClipBounds();

			if (paintUpperPart) {
				// clip to paint only the upper part of this building
				g.setClip(x - spriteInfo.getOriginX(), y - spriteInfo.getOriginY(),
						animation.getImageWidth(), spriteInfo.getOriginY());
			} else if (paintLowerPart) {
				// clip to paint only the lower part of this building
				g.setClip(x - spriteInfo.getOriginX(), y, animation.getImageWidth(),
						animation.getImageHeight() - LevelProperties.getGridSize());
			}

			// paint the sprite
			renderer.paint(g, x - spriteInfo.getOriginX(), y
					- spriteInfo.getOriginY());

			// reset the old clip rectangle
			g.setClip(oldClip);

			// paint the healthbar only on the upper part
			if ((selected || healthBarVisible) && paintLowerPart) {
				Renderers.getHealthBarRenderer().paint(g, x,
						y - spriteInfo.getOriginY(), health, width, 8);
			}
		}
	}

}
